<?php

namespace app\merchant\controller;

use app\admin\model\Goods as ModelGoods;
use app\admin\model\MerchantAccount;
use app\admin\model\MerchantWithdrawApply;
use app\admin\model\UserMerchant;
use think\facade\View;
use app\common\services\RedisService;
use app\common\Tools;
use app\Request;
use think\facade\Db;

//财务
class Finance extends Base 
{

    //首页
    public function finance_cash(){
        $merchant_account = MerchantAccount::where('merchant_id', $this->uid)->find();
        $merchant         = UserMerchant::find($this->uid);
        view::assign('merchant_account_exits', $merchant_account ? true : false);
        view::assign('merchant_account', $merchant_account);
        view::assign('merchant', $merchant);
        return View::fetch();
    }

    public function finance_account(){
        $merchant_account = MerchantAccount::where('merchant_id', $this->uid)->find();
        $bank_codes  = Db::name('banks')->select();
        view::assign('merchant_account', $merchant_account);
        view::assign('bank_codes', $bank_codes);
        return View::fetch();
    }



    public function finance_log(){
        return View::fetch();
    }

    public function finance_logs(){
        return View::fetch();
    }


    //保存收款账号
    public function save_finance_account(Request $request){
        $redis_service = RedisService::getInstance();
        $lock_key = "api:save_finance_account:" . $this->uid;

        try {
            $action_lock = $redis_service->acquireLock($lock_key, 3); // 原子设置+过期时间
            if (!$action_lock) {
                exception('请勿重复提交');
            }

            $post_data = $request->postMore([
                ['account_user', ''],
                ['account', ''],
                ['password', ''],
                ['enc_bank_no', ''],
                ['enc_true_name', ''],
                ['bank_code', ''],
                ['password', ''],
                ['re_password', ''],
            ]);

            Tools::check($post_data, [
                'account_user' => 'require',
                'password' => 'require',
                'enc_bank_no' => 'require',
                'enc_true_name' => 'require',
                'bank_code' => 'require',
            ], [
                'account_user.require' => '收款人不得为空',
                'password.require' => '密码不得为空',
                'enc_bank_no.require' => '银行卡号不得为空',
                'enc_true_name.require' => '收款人不得为空',
                'bank_code.require' => '开户行不得为空',
            ]);
            if($post_data['password'] !== $post_data['re_password']) {
                exception('两次密码输入不一致');
            }
            $exists = MerchantAccount::where('merchant_id', $this->uid)->find();
            if($exists) {
                $exists->account_user = $post_data['account_user'];
                $exists->account_type = 3;
                $exists->account = $post_data['account'];
                $exists->password = md5($post_data['password']);
                $exists->enc_bank_no = $post_data['enc_bank_no'];
                $exists->enc_true_name = $post_data['enc_true_name'];
                $exists->bank_code = $post_data['bank_code'];
                $exists->save(); 
            }else{
                $exists = new MerchantAccount();
                $exists->merchant_id = $this->uid;
                $exists->account_user = $post_data['account_user'];
                $exists->account_type = 3;
                $exists->account = $post_data['account'];
                $exists->password = md5($post_data['password']);
                $exists->enc_bank_no = $post_data['enc_bank_no'];
                $exists->enc_true_name = $post_data['enc_true_name'];
                $exists->bank_code = $post_data['bank_code'];
                $exists->save();
            }
        } catch (\Exception $e) {
            return app('json')->fail($e->getMessage());

        } finally {
            // 🧹 无论成功与否，释放锁
            $redis_service->releaseLock($lock_key);
        }

        return app('json')->success('操作成功');
    }

    //提现申请
    public function withdraw_apply(Request $request){
        $redis_service = RedisService::getInstance();
        $lock_key = "api:withdraw_apply:" . $this->uid;

        try {
            $action_lock = $redis_service->acquireLock($lock_key, 3); // 原子设置+过期时间
            if (!$action_lock) {
                exception('请勿重复提交');
            }
          
            $merchant_account = MerchantAccount::where('merchant_id', $this->uid)->find();
            if(!$merchant_account) {
                exception('请先设置收款账号');
            }
            $post_data = $request->postMore([
                ['amount', ''],
                ['trade_password', ''],
         
                ['account_user', ''],
            ]);

            Tools::check($post_data, [
                'amount' => 'require',
                'trade_password' => 'require',
           
                'account_user' => 'require',
            ], [
                'amount.require' => '金额不得为空',
                'trade_password.require' => '交易密码不得为空',
                'account_user.require' => '收款人不得为空',
                'account.require' => '收款账号不得为空',
            ]);
            $merchant  = UserMerchant::where('id', $this->uid)->lock(true)->find();
            if(!$merchant) {
                exception('商户不存在');
            }
            if($merchant_account->password !== md5($post_data['trade_password'])) {
                exception('交易密码错误');
            }
            if($merchant->balance < $post_data['amount']) {
                exception('余额不足');
            }
            $withdraw_min = (float)freshCache('merchant.withdraw_min');
            $withdraw_max = (float)freshCache('merchant.withdraw_max');
            if($post_data['amount'] < $withdraw_min) {
                exception('提现金额不得小于' . $withdraw_min);
            }
            if($post_data['amount'] > $withdraw_max) {
                exception('提现金额不得大于' . $withdraw_max);
            }
            $commission_rate = (float)freshCache('merchant.commission_rate'); //手续费
            $withdraw_apply_limit_day = (int)freshCache('merchant.withdraw_apply_limit_day'); //每日提现次数限制
            $withdraw_apply_limit_month = (int)freshCache('merchant.withdraw_apply_limit_month'); //每月提现次数限制
            $commission_price = $post_data['amount'] * $commission_rate / 100;
            if(MerchantWithdrawApply::where('merchant_id',$this->uid)->whereDay('create_time')->count() >= $withdraw_apply_limit_day) {
                exception('您今日提现次数已达上限');
            }
            if(MerchantWithdrawApply::where('merchant_id',$this->uid)->whereMonth('create_time')->count() >= $withdraw_apply_limit_month) {
                exception('您本月提现次数已达上限');
            }
            $merchant->balance = $merchant->balance - $post_data['amount'];
            $merchant->save();
            MerchantWithdrawApply::create([
                'merchant_id' => $this->uid,
                'amount' => $post_data['amount'],
                'commission' => $commission_price,
                'real_amount' => $post_data['amount'] - $commission_price,
                'enc_bank_no' => $merchant_account->enc_bank_no,
                'enc_true_name' => $merchant_account->enc_true_name,
                'bank_code' => $merchant_account->bank_code,
                'status' => 0,
            ]);
        } catch (\Exception $e) {
            return app('json')->fail($e->getMessage());

        } finally {
            // 🧹 无论成功与否，释放锁
            $redis_service->releaseLock($lock_key);
        }

        return app('json')->success('操作成功');
    }


     //提现申请
     public function finance_cancel(Request $request){
        $redis_service = RedisService::getInstance();
        $lock_key = "api:finance_cancel:" . $this->uid;

        try {
            $action_lock = $redis_service->acquireLock($lock_key, 3); // 原子设置+过期时间
            if (!$action_lock) {
                exception('请勿重复提交');
            }

            $post_data = $request->postMore([
                ['id', ''],
            ]);

            Tools::check($post_data, [
                'id' => 'require',
            ], [
                'id.require' => 'ID不得为空',
            ]);
            $log = MerchantWithdrawApply::where('merchant_id',$this->uid)->where('id',$post_data['id'])->find();
            if(!$log) {
                exception('申请记录不存在');
            }
            if($log->status !=0){
                exception('只能取消待审核的申请记录');
            }
           $log->status = 3;
           $log->save();
        } catch (\Exception $e) {
            return app('json')->fail($e->getMessage());

        } finally {
            // 🧹 无论成功与否，释放锁
            $redis_service->releaseLock($lock_key);
        }

        return app('json')->success('操作成功');
    }

    //列表
    public function get_finance_log(Request $request){
        $post_data = $request->getMore([
            ['page', 1],
            ['limit', 10],
            ['keyword', ''],
            ['status']
        ]);
        $query = MerchantWithdrawApply::where('merchant_id',$this->uid)
            ->when($post_data['keyword'], function ($query) use ($post_data) {
                $query->where('name', 'like', '%' . $post_data['keyword'] . '%');
            })
            ->when($post_data['status'] !== null, function ($query) use ($post_data) {
                $query->where('status', $post_data['status']);
            });
            $list = $query->page($post_data['page'], $post_data['limit'])->order('id desc')->append(['status_text'])->select()->toArray();
            $count = $query->count();
            $list = $query->page($post_data['page'], $post_data['limit'])->order('id desc')->append(['status_text'])->select()->toArray();
        if(count($list)){
            foreach($list as &$item){
                $item['bank_name'] = Db::name('banks')->where('bank_code',$item['bank_code'])->value('bank_name');
            }
        }
        return app('json')->layuiTableResponse('ok',$list,$count);
    }


    public function upload(){
        $file_servrt = new \app\admin\controller\Upload();
        $file_servrt->upload_file();
    }
}
